<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>触摸拖拽</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            html,
            body,
            #app {
                width: 100vw;
                height: 100vh;
                overflow: hidden;
            }

            #move {
                width: 150px;
                height: 150px;
                border: solid 1px #666;
                position: absolute;
                transition: all 0.5s;
            }
        </style>
    </head>
    <body>
        <div id="app"> <div id="move"></div> </div>

        <script>
            //获取元素
            let app = document.querySelector("#app");
            let move = document.querySelector("#move");

            //绑定事件
            move.addEventListener("touchstart", function (e) {
                //获取元素距离左侧的偏移量
                this.l = move.offsetLeft; //
                this.x = e.changedTouches[0].pageX;

                this.t = move.offsetTop;
                this.y = e.changedTouches[0].pageY;

                this.style.transition = "none";
            });

            move.addEventListener("touchmove", function (e) {
                let _x = e.changedTouches[0].pageX;
                let _y = e.changedTouches[0].pageY;

                //计算最终的 left
                let newLeft = _x - (this.x - this.l);
                let newTop = _y - (this.y - this.t);
                //计算最小left
                if (newLeft <= 0) newLeft = 0;
                //计算最大的left
                let maxLeft = app.offsetWidth - move.offsetWidth;
                if (newLeft >= maxLeft) newLeft = maxLeft;
                //设置
                move.style.left = newLeft + "px";
                move.style.top = newTop + "px";
            });

            move.addEventListener("touchend", function () {
                this.style.transition = "all 0.5s";

                //计算居中时, left 值
                let middle = (app.offsetWidth - move.offsetWidth) / 2;
                //判断
                if (move.offsetLeft < middle) {
                    //居左
                    move.style.left = "0px";
                } else {
                    //居右 可能居中
                    move.style.left = app.offsetWidth - move.offsetWidth + "px";
                }
            });
        </script>
    </body>
</html>
